package com.example.dingtalklogin.common.util;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.util.Map;
import java.util.Objects;

/**
 * Jackson工具类
 * @author xuzhe
 */
public class JacksonUtil {
    public static ObjectMapper objectMapper = new ObjectMapper();

    /**
     * 使用泛型方法，把json字符串转换为相应的JavaBean对象。
     * (1)转换为普通JavaBean：readValue(json,Student.class)
     * (2)转换为List,如List<Student>,将第二个参数传递为Student
     * [].class.然后使用Arrays.asList();方法把得到的数组转换为特定类型的List
     *
     * @param jsonStr
     * @param valueType
     * @return
     */
    public static <T> T readValue(String jsonStr, Class<T> valueType) {
        try {
            return objectMapper.readValue(jsonStr, valueType);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }

    /**
     * json数组转List
     * @param jsonStr
     * @param valueTypeRef
     * @return
     */
    public static <T> T readValue(String jsonStr, TypeReference<T> valueTypeRef){
        try {
            return objectMapper.readValue(jsonStr, valueTypeRef);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 把JavaBean转换为json字符串
     *
     * @param object
     * @return
     */
    public static String toJson(Object object) {
        try {
            return objectMapper.writeValueAsString(object);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * diff 比较老的对象json和新的对象json中value值的差别
     * @param oldObjStr
     * @param newObjStr
     * @return
     */
    public static String diff(String oldObjStr, String newObjStr){
        Map<String, Object> oldObjMap = readValue(oldObjStr, Map.class);
        Map<String, Object> newObjMap = readValue(newObjStr, Map.class);
        if(oldObjMap != null && newObjMap != null){
            StringBuilder diffBuilder = new StringBuilder();
            for(Map.Entry<String,Object> entry : oldObjMap.entrySet()){
                Object oldValue = entry.getValue();
                Object newValue = newObjMap.get(entry.getKey());
                // 新对象中有值，但是和老对象中的值不一致，需要记录
                if(newValue != null && !Objects.equals(oldValue, newValue)){
                    diffBuilder.append("[key=" + entry.getKey() + ",oldValue=" + oldValue + ",newValue=" + newValue + "];");
                }
            }
            return diffBuilder.toString();
        }
        return null;
    }
}

